<?php

namespace app\api\controller;

use app\admin\model\BillModel;
use app\admin\model\Building;
use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomFixedModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\ContractBoardModel;
use app\admin\model\ContractFixedModel;
use app\admin\model\ContractPtModel;
use app\admin\model\CustomerModel;
use app\admin\model\HouseModel;
use app\admin\model\HouseOwnerModel;
use app\common\controller\Api;
use app\common\model\Contract as ThisModel;
use app\common\model\ContractError;
use app\common\model\Message;
use app\common\model\OrderPaymentRecords;
use app\common\model\PaymentRecords;
use app\common\model\User;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 合同接口
 */
class Contract extends Api
{
    protected $noNeedLogin = ['getType'];
    protected $noNeedRight = '*';

    /**
     * @brief   添加合同
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function add()
    {
        $getData = $params = $this->request->post();
        $keys = $this->get_keys('add' . $this->auth->id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }

        $getData['type'] = 2;
        $validate = new \app\api\validate\v2\Contract();
        $check_result = $validate->scene('add')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        $room_id = $getData['room_id'];
        $room_info = BuildingRoomModel::get($room_id);
        if (!$room_info) {
            $this->del_rekey($keys);
            $this->error('房间不存在');
        }
        if ($room_info['status'] == 3) {
            $this->del_rekey($keys);
            $this->error('房间已签约');
        }
        $build_info = Building::get($room_info['build_id']);
        if (!$build_info) {
            $this->del_rekey($keys);
            $this->error('获楼栋失败');
        }


        $homeowner_id = explode(',', $build_info->user_id)[0] ?? 0;
        $homeowner_user = User::get($homeowner_id);
        $homeowner_phone = $homeowner_user->mobile ?? '';

        //检测房东是否认证
        $homeowner_re = HouseOwnerModel::where(['user_id' => $homeowner_id])->find();
        if (!$homeowner_re) {
            $this->del_rekey($keys);
            $this->error('获房东认证信息失败');
        }
        if ($homeowner_re['status'] != 1) {
            $this->del_rekey($keys);
            $this->error('房东认证状态异常');
        }
        $homeowner_info = [
            'homeowner_name' => $homeowner_re['real_name'],
            'homeowner_idcard' => $homeowner_re['card_no'],
            'house_address' => $build_info['address'],
            'homeowner_phone' => $homeowner_phone,
        ];

        if (!empty($getData['photo'])) {
            $photos = explode(',', $getData['photo']);
            foreach ($photos as $v) {
                $ext_arr = explode('.', $v);
                if (!in_array($ext_arr[count($ext_arr) - 1], ['png', 'jpeg', 'jpg'])) {
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data = ['photo' => $v];
                $check_result = $validate->scene('add_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }

        $user_info = User::where(['mobile' => $getData['user_phone']])->find();
        if (!$user_info) {
            $this->del_rekey($keys);
            $this->error('租户未注册');
        }
        if ($user_info['id'] == $homeowner_id) {
            $this->del_rekey($keys);
            $this->error('不能与自己签合同');
        }

        $getData['user_id'] = $user_info['id'] ?? 0;

        $house = HouseModel::get([
            'room_id' => $room_id,
            'is_finish' => 0,
        ]);

        $insert_data = [
            'house_id' => $house->id ?? 0,
            'build_id' => $build_info->id ?? 0,
            'homeowner_id' => $homeowner_id,
            'homeowner_name' => $homeowner_info['homeowner_name'],
            'homeowner_idcard' => $homeowner_info['homeowner_idcard'],
            'homeowner_phone' => $homeowner_info['homeowner_phone'],
            'house_address' => $homeowner_info['house_address'],
            'money_zu' => $getData['money_zu'] ?? 0,
            'money_ya' => $getData['money_ya'] ?? 0,
            'ya_type' => $getData['ya_type'] ?? 0,
            'water_num' => $getData['water_num'] ?? 0,
            'electricity_num' => $getData['electricity_num'] ?? 0,
            'pay_time' => $getData['pay_time'] ?? '',
            'money_electricity' => $getData['money_electricity'] ?? 0,
            'money_water' => $getData['money_water'] ?? 0,
            'photo' => $getData['photo'] ?? '',
            'status' => 0,
            'create_user_id' => $this->auth->id,
        ];
        //检测该房源是否有生效的合同
        $contract_info = ThisModel::where([
            'homeowner_id' => $insert_data['homeowner_id'],
            'room_id' => $room_id,
            'status' => ['in', [0, 1]]
        ])->find();
        if ($contract_info) {
            $this->error('房源已签约');
        }
        $renter_name = $user_info['username'] ?? $getData['user_name'];
        $insert_data['name'] = $insert_data['homeowner_name'] . '与' . $renter_name . '的合同';
        $insert_data['build_address'] = $build_info['address'];
        $insert_data['build_name'] = $build_info['name'];
        $insert_data['room_name'] = $room_info['name'];
        $insert_data['now_count'] = 0;
        $insert_data['moon_fang_data'] = date('Y-m-d', strtotime(date('Y-m')));;
        $insert_data['createtime'] = time();

        $message_data = [
            'type' => Message::TYPE_TWO,
            'user_id' => $getData['user_id'],
            'title' => '您的合同已签订',
            'content' => '您的合同内容',
        ];
        $res = false;
        try {
            Db::startTrans();
            //推送缴费消息
            $insert_data = array_merge($getData, $insert_data);
            $contract = ThisModel::create($insert_data, true);
            $contract_id = $contract->id;
            $message_data['other_id'] = $contract_id;
            Message::add($message_data);
            //修改房屋状态
            HouseModel::where([
                'room_id' => $room_id,
                'is_finish' => 0
            ])
                ->update([
                    'status' => 2,
                    'is_finish' => 1
                ]);

            // 更新房间状态
            $room_info->save(['status' => 2]);


            if (!empty($params['board'])) {
                array_walk($params['board'], function (&$item, $key) use ($room_id, $contract_id) {
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);

                (new ContractBoardModel())->allowField(true)->saveAll($params['board']);
            }
            if (!empty($params['fixed'])) {
                array_walk($params['fixed'], function (&$item, $key) use ($room_id, $contract_id) {
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);
                (new ContractFixedModel())->allowField(true)->saveAll($params['fixed']);
            }

            if (!empty($params['pt'])) {
                array_walk($params['pt'], function (&$item, $key) use ($room_id, $contract_id) {
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);
                (new ContractPtModel())->allowField(true)->saveAll($params['pt']);
            }
            $this->addCustomerByContract($contract);
            $res = true;
            $in_record['countent'] = "创建合同".$contract_id;
            $in_record['ord_id'] = $contract_id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            Db::name("record")->insertGetId($in_record);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('创建合同失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
        }
        $this->del_rekey($keys);
        if (!$res) {
            $this->error('提交失败');
        }

            $this->success('提交成功', ['contract_id' => $contract_id ?? 0]);
    }


    public function edit()
    {
        $getData = $params = $this->request->param();
        $id = $this->request->param('id/d', 0);
        $room_id = $this->request->param('room_id/d', 0);
        if ($id < 1 && $room_id < 1) {
            $this->error('参数错误');
        }

        if ($room_id) {
            $contract = ThisModel::where([
                'room_id' => $room_id,
            ])->order('id', 'desc')->find();
        } else {
            $contract = ThisModel::get($id);
        }

        if (empty($contract)) {
            $this->error('合同不存在');
        }

        $user_id = $this->auth->id;
        $keys = $this->get_keys('add' . $user_id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }

        $validate = new \app\api\validate\v2\Contract();
        $check_result = $validate->scene('add')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        $room_id = $getData['room_id'];
        $room_info = BuildingRoomModel::get($room_id);
        if (!$room_info) {
            $this->del_rekey($keys);
            $this->error('房间不存在');
        }

        $build_info = Building::get($room_info['build_id']);
        if (!$build_info) {
            $this->del_rekey($keys);
            $this->error('获楼栋失败');
        }
        //检测房东是否认证
        $homeowner_id = $contract->homeowner_id;
        $homeowner_re = HouseOwnerModel::where(['user_id' => $homeowner_id])->find();
        if (!$homeowner_re) {
            $this->del_rekey($keys);
            $this->error('获房东认证信息失败');
        }
        if ($homeowner_re['status'] != 1) {
            $this->del_rekey($keys);
            $this->error('房东认证状态异常');
        }

        $homeowner_user = User::get($homeowner_id);
        $homeowner_phone = $homeowner_user->mobile ?? '';


        $homeowner_info = [
            'homeowner_name' => $homeowner_re['real_name'],
            'homeowner_idcard' => $homeowner_re['card_no'],
            'house_address' => $build_info['address'],
            'homeowner_phone' => $homeowner_phone,
        ];


        if (!empty($getData['photo'])) {
            $photos = explode(',', $getData['photo']);
            foreach ($photos as $v) {
                $ext_arr = explode('.', $v);
                if (!in_array($ext_arr[count($ext_arr) - 1], ['png', 'jpeg', 'jpg'])) {
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data = ['photo' => $v];
                $check_result = $validate->scene('add_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }

        $user_info = User::where(['mobile' => $getData['user_phone']])->find();
        if (!$user_info) {
            $this->del_rekey($keys);
            $this->error('租户未注册');
        }
        if ($user_info && $user_info['id'] == $homeowner_id) {
            $this->del_rekey($keys);
            $this->error('不能与自己签合同');
        }
        $getData['user_id'] = $user_info['id'] ?? 0;

        $house = HouseModel::where([
            'room_id' => $room_id,
        ])->order('id', 'desc')->find();

        if (!empty($getData['roommate'])) {
            $roommate = $getData['roommate'];
            $roommate = array_values(array_unique(explode(',', $roommate)));
            $getData['roommate'] = trim(implode(',', $roommate), ',');
        }
        $countent = '';
        if(isset($homeowner_info['homeowner_name'])){
            if($contract->homeowner_name != $homeowner_info['homeowner_name']){
                $countent .= "|原房东姓名：".$contract->homeowner_name;
            }
        }
        if(isset($homeowner_info['homeowner_idcard'])) {
            if ($contract->homeowner_idcard != $homeowner_info['homeowner_idcard']) {
                $countent .= "|原房东身份证号：" . $contract->homeowner_idcard;
            }
        }
        if(isset($homeowner_info['homeowner_phone'])) {
            if ($contract->homeowner_phone != $homeowner_info['homeowner_phone']) {
                $countent .= "原房东手机号：" . $contract->homeowner_phone;
            }
        }
        if(isset($getData['money_zu'])) {
            if ($contract->money_zu != $getData['money_zu']) {
                $countent .= "|原房租：" . $contract->money_zu;
            }
        }
        if(isset($getData['water_num'])) {
            if ($contract->water_num != $getData['water_num']) {
                $countent .= "原水表数：" . $contract->water_num;
            }
        }
        if(isset($getData['electricity_num'])) {
            if ($contract->electricity_num != $getData['electricity_num']) {
                $countent .= "|原电表数：" . $contract->electricity_num;
            }
        }
        if(isset($getData['money_electricity'])) {
            if ($contract->money_electricity != $getData['money_electricity']) {
                $countent .= "|原电费：" . $contract->money_electricity;
            }
        }
        if(isset($getData['money_water'])) {
            if ($contract->money_water != $getData['money_water']) {
                $countent .= "|原水费：" . $contract->money_water;
            }
        }
        if(isset($getData['rent_way'])) {
            if ($contract->rent_way != $getData['rent_way']) {
                $wa_name = '';
                if($contract->rent_way == 1){
                    $wa_name = "每月";
                }elseif($contract->rent_way == 2){
                    $wa_name = "每2月";
                }elseif($contract->rent_way == 3){
                    $wa_name = "每3月";
                }

                $countent .= "|原交租方式：" .$wa_name;
            }
        }
        if(isset($getData['rent_day'])) {
            if ($contract->rent_day != $getData['rent_day']) {
                $countent .= "|原交房日：" . $contract->rent_day;
            }
        }
        if(isset($getData['ahead_day'])) {
            if ($contract->ahead_day != $getData['ahead_day']) {
                $countent .= "|原提前天数：" . $contract->ahead_day;
            }
        }
        if(isset($getData['user_type'])) {
            if ($contract->user_type != $getData['user_type']) {
                $countent .= "|原租客类型：" . $contract->user_type==1?"个人":"企业";
            }
        }
        if(isset($getData['user_card'])) {
            if ($contract->user_card != $getData['user_card']) {
                $countent .= "|原租客身份证号：" . $contract->user_card;
            }
        }
        if(isset($getData['user_phone'])) {
            if ($contract->user_phone != $getData['user_phone']) {
                $countent .= "|原租客手机号：" . $contract->user_phone;
            }
        }
        if(isset($getData['user_name'])) {
            if ($contract->user_name != $getData['user_name']) {
                $countent .= "|原租客姓名：" . $contract->user_name;
            }
        }
        if(isset($getData['sex'])) {
            if ($contract->sex != $getData['sex']) {
                $countent .= "|原租客性别：" . $contract->sex==1?"男":"女";
            }
        }
        if(isset($getData['ahead_day'])) {
            if ($contract->ahead_day != $getData['ahead_day']) {
                $countent .= "|原提前天数：" . $contract->ahead_day;
            }
        }
        if(isset($getData['money_ya'])) {
            if ($contract->money_ya != $getData['money_ya']) {
                $countent .= "|原押金：" . $contract->money_ya;
            }
        }
        if(isset($getData['first_zu'])) {
            if ($contract->first_zu != $getData['first_zu']) {
                $countent .= "|原首次房租：" . $contract->first_zu;
            }
        }
        if(isset($getData['start_time'])) {
            if ($contract->start_time != $getData['start_time']) {
                $countent .= "|原开始时间：" . $contract->start_time;
            }
        }
        if(isset($getData['end_time'])) {
            if ($contract->end_time != $getData['end_time']) {
                $countent .= "|原结束时间：" . $contract->end_time;
            }
        }
        $insert_data = [
            'house_id' => $house->id ?? 0,
            'build_id' => $build_info->id ?? 0,
            'homeowner_id' => $homeowner_id,
            'homeowner_name' => $homeowner_info['homeowner_name'],
            'homeowner_idcard' => $homeowner_info['homeowner_idcard'],
            'homeowner_phone' => $homeowner_info['homeowner_phone'],
            'house_address' => $homeowner_info['house_address'],
            'money_zu' => $getData['money_zu'] ?? 0,
            'money_ya' => $getData['money_ya'] ?? 0,
            'ya_type' => $getData['ya_type'] ?? 0,
            'water_num' => $getData['water_num'] ?? 0,
            'electricity_num' => $getData['electricity_num'] ?? 0,
            'pay_time' => $getData['pay_time'] ?? '',
            'money_electricity' => $getData['money_electricity'] ?? 0,
            'money_water' => $getData['money_water'] ?? 0,
            'photo' => $getData['photo'] ?? '',
        ];
        $renter_name = $user_info['username'] ?? $getData['user_name'];
        $insert_data['name'] = $insert_data['homeowner_name'] . '与' . $renter_name . '的合同';

        $insert_data['build_address'] = $build_info['address'];
        $insert_data['build_name'] = $build_info['name'];
        $insert_data['room_name'] = $room_info['name'];
        $insert_data['now_count'] = 0;

        $message_data = [
            'type' => Message::TYPE_TWO,
            'user_id' => $getData['user_id'],
            'title' => '您的合同已更新',
            'content' => '您的合同内容',
        ];
        $res = false;
        try {
            Db::startTrans();
            $in_record['countent'] = "修改合同".trim($countent,'|');
            $in_record['ord_id'] = $contract->id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            Db::name("record")->insertGetId($in_record);

            //推送缴费消息
            $insert_data = array_merge($getData, $insert_data);
            $contract->allowField(true)->save($insert_data);
            $contract_id = $contract->id;
            $message_data['other_id'] = $contract_id;
            Message::add($message_data);
            //修改房屋状态
            HouseModel::where([
                'room_id' => $room_id,
                'is_finish' => 0
            ])
                ->update([
                    'status' => 2,
                    'is_finish' => 1
                ]);

            // 更新房间
            //$room_info->save(['status' => 2]);

            ContractBoardModel::destroy(['room_id' => $room_id]);
            if (!empty($params['board'])) {
                array_walk($params['board'], function (&$item, $key) use ($room_id, $contract_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);

                (new ContractBoardModel())->allowField(true)->saveAll($params['board']);
            }
            ContractFixedModel::destroy(['room_id' => $room_id]);
            if (!empty($params['fixed'])) {
                array_walk($params['fixed'], function (&$item, $key) use ($room_id, $contract_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);
                (new ContractFixedModel())->allowField(true)->saveAll($params['fixed']);
            }
            ContractPtModel::destroy(['room_id' => $room_id]);
            if (!empty($params['pt'])) {
                array_walk($params['pt'], function (&$item, $key) use ($room_id, $contract_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                    $item['contract_id'] = $contract_id;
                }, $room_id);
                (new ContractPtModel())->allowField(true)->saveAll($params['pt']);
            }

            $this->addCustomerByContract($contract);

            $res = true;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('更新合同失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
        }
        $this->del_rekey($keys);
        if (!$res) {
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }


    private function addCustomerByContract($contract)
    {
        $count = CustomerModel::where([
            'user_id' => $this->auth->id,
            'mobile' => $contract->user_phone
        ])->count();

        if ($count) {
            return true;
        }

        CustomerModel::create([
            'user_id' => $this->auth->id,
            'name' => $contract->user_name,
            'mobile' => $contract->user_phone,
            'contact_name' => $contract->contact_name,
            'type' => $contract->user_type,
            'id_card' => $contract->user_card,
            'card_image' => $contract->user_card_img,
        ], true);
        return true;
    }


    public function add_roommate()
    {
        $contract_id = $this->request->param('contract_id/d', 0);
        $customer_id = $this->request->param('customer_id/d');
        if ($contract_id < 1) {
            $this->error('合同id不能为空');
        }

        if (empty($customer_id)) {
            $this->error('客户id不能为空');
        }


        $contract = ThisModel::get($contract_id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }

        Db::startTrans();
        try {
            $arr = explode(',', $contract->roommate);
            $arr[] = $customer_id;
            $roommate = array_values(array_unique($arr));
            $contract->roommate = trim(implode(',', $roommate), ',');
            $contract->save();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }


    public function change_room()
    {
        $id = $this->request->param('contract_id/d', 0);
        $room_id = $this->request->param('room_id/d', 0);
        $money_zu = $this->request->param('money_zu/f', 0);
        if ($id < 1 || $room_id < 1 || $money_zu <= 0) {
            $this->error('参数错误');
        }

        $contract = ThisModel::get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }

        Db::startTrans();
        try {

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }


    public function revoke_audit()
    {
        $id = $this->request->param('contract_id/d', 0);

        if ($id < 1) {
            $this->error('参数错误');
        }

        $contract = ThisModel::get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }

        Db::startTrans();
        try {

            BillModel::destroy([
                'contract_id' => $id,
                'status' => ['in', [0, 1]],
            ]);

            BillModel::destroy([
                'contract_id' => $id,
                'type' => 2,
            ]);

            PaymentRecords::destroy([
                'homeowner_id' => $contract->homeowner_id,
                'contract_id' => $contract->id,
                'user_id' => $contract->user_id,
                'type' => PaymentRecords::TYPE_FANG,
                'status' => PaymentRecords::STATUS_DEFAULT,
            ]);

            $contract->status = 0;
            $contract->save();

            $in_record['countent'] = "撤回审核";
            $in_record['ord_id'] = $contract->id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);
            // 更新房间状态
            $room = BuildingRoomModel::get($contract->room_id);
            if ($room) {
                $room->status = 2;
                $room->save();
            }

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }



    public function cancel()
    {
        $id = $this->request->param('contract_id/d', 0);

        if ($id < 1) {
            $this->error('参数错误');
        }

        $contract = ThisModel::get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }

        Db::startTrans();
        try {

            BillModel::destroy([
                'contract_id' => $id,
                'status' => ['in', [0, 1]],
                'type' => 1,
            ]);

            BillModel::destroy([
                'contract_id' => $id,
                'type' => 2,
            ]);

            // 重置房间
            $room = BuildingRoomModel::get($contract->room_id);
            if ($room) {
                $room->status = 0;
                $room->save();
            }
            $in_record['countent'] = "重置房间";
            $in_record['ord_id'] = $id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);

            $contract->status = 3;
            $contract->save();

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }


    public function audit()
    {
        $id = $this->request->param('id/d', 0);
        if ($id < 1) {
            $this->error('参数错误');
        }

        $contract = ThisModel::get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }
        Db::startTrans();
        try {
            // =========  生成账单 =========
            //首次租金
            $rent_date = date('Y-m-' . $contract['rent_day']);
            $period = date('Y-m-d') . '至' . date('Y-m-d', strtotime('next month -1 day', strtotime($rent_date)));

            $first_money = $contract['first_zu'];
            //$fixed_money = BuildingRoomFixedModel::where('room_id', $contract['room_id'])->sum('price');

            //$first_money = bcadd($first_money, $fixed_money, 2);

            if ($first_money > 0) {
                $other_data = [
                    [
                        'name' => '首次租金',
                        'money' => $first_money,
                    ]
                ];
                $bill = BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 0,
                    'money' => $first_money,
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => '租金',
                    'type' => 1,
                    'remark' => '首次租金',
                    'period' => $period,
                    'is_first' => 1,
                    'other_data' => json_encode($other_data,JSON_UNESCAPED_UNICODE),
                ], true);
                //收支创建
                $add_data['user_id'] = $contract['homeowner_id'];
                $add_data['type'] = 2;
                $add_data['money'] = $first_money;
                //$add_data['classify_id'] = $classify_id;
                //$add_data['ledger_id'] = $ledger_id;
                //$add_data['account_id'] = $account_id;
                $add_data['in_date'] = date('Y-m-d',time());
                //$add_data['images'] = $images;
                $add_data['house_id'] = $contract['house_id'];
                $add_data['remarks'] = '房租押金';
                $add_data['str_type'] = '租金';
                $add_data['createtime'] = time();
                Db::name("szinfo")->insertGetId($add_data);


                PaymentRecords::create([
                    'homeowner_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'relation_id' => $bill->id,
                    'user_id' => $contract->user_id,
                    'type' => PaymentRecords::TYPE_FANG,
                    'status' => PaymentRecords::STATUS_DEFAULT,
                    'money' => $first_money,
                ],true);
            }

            // 房租押金
            if ($contract['money_ya'] > 0) {
                BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 2,
                    'money' => $contract['money_ya'],
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => '押金',
                    'type' => 2,
                    'remark' => '房租押金',
                    'expire_date' => $contract['end_time'],
                ]);
                //收支创建
                $add_data['user_id'] = $contract['homeowner_id'];
                $add_data['type'] = 2;
                $add_data['money'] = $contract['money_ya'];
                //$add_data['classify_id'] = $classify_id;
                //$add_data['ledger_id'] = $ledger_id;
                //$add_data['account_id'] = $account_id;
                $add_data['in_date'] = date('Y-m-d',time());
                //$add_data['images'] = $images;
                $add_data['house_id'] = $contract['house_id'];
                $add_data['remarks'] = '房租押金';
                $add_data['str_type'] = '房租押金';
                $add_data['createtime'] = time();
                Db::name("szinfo")->insertGetId($add_data);
            }


            // 配套押金
            if (!empty($contract['pt'])) {
                $pt_money = array_sum(array_column($contract['pt'], 'deposit'));
                if ($pt_money > 0) {
                    BillModel::create([
                        'user_id' => $contract['homeowner_id'],
                        'contract_id' => $id,
                        'status' => 2,
                        'money' => $pt_money,
                        'year' => date('Y'),
                        'month' => date('Y-m'),
                        'day' => date('Y-m-d'),
                        'category' => '押金',
                        'type' => 2,
                        'remark' => '配套设备押金',
                        'expire_date' => $contract['end_time'],
                    ]);
                }
            }

            $contract->status = 1;
            $contract->save();


            $in_record['countent'] = "审核";
            $in_record['ord_id'] = $contract->id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);
            // 更新房间状态
            $room = BuildingRoomModel::get($contract->room_id);
            $room->status = 3;
            $room->save();



            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            trace('合同审核失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * @brief   获取合同押金方式
     * @return void
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function getYaTypeList()
    {
        $list = ThisModel::getYaTypeList();
        $this->success('获取成功', $list);
    }

    /**
     *  获取合同列表(房东)
     *
     */
    public function contractLists()
    {
        $type = $this->request->param('type/d');
        $page_size = $this->request->param('page_size/d', 15);
        $room_id = $this->request->param('room_id/d', 0);
        $build_ids = BuildingModel::getUserBuildingIds($this->auth->id);

        $where = [];
        $where['build_id'] = ['in', $build_ids];
        if ($room_id) {
            $where['room_id'] = $room_id;
        }
        if ($type == 1) {
            $where['status'] = 0;
        } elseif ($type == 2) {
            $where['status'] = 1;
        } elseif ($type == 3) {
            //提醒
            $room_ids = BuildingRoomModel::where([
                'build_id' => ['in', $build_ids],
                'is_remind' => 1
            ])->column('id');
            $where['room_id'] = ['in', $room_ids];
        } elseif ($type == 4) {
            $where['status'] = 2;
        }
        $list = ThisModel::where($where)
            ->field('id,build_name,build_address,room_name,money_zu,status')
            ->order('id desc')
            ->paginate($page_size);

        $this->success('成功', $list);
    }

    // 历史合同
    public function history_contract()
    {
        $room_id = $this->request->param('room_id/d', 0);
        $page_size = $this->request->param('page_size/d', 15);
        $build_ids = BuildingModel::getUserBuildingIds($this->auth->id);

        $where = [];
        $where['build_id'] = ['in', $build_ids];
        $where['room_id'] = $room_id;
        $list = ThisModel::where($where)
            ->field('id,build_address,room_name,money_zu,status,user_name,user_phone,createtime')
            ->order('id desc')
            ->paginate($page_size);

        $this->success('成功', $list);
    }

    // 房东合同列表数据统计
    public function contractListStat()
    {
        $build_ids = BuildingModel::getUserBuildingIds($this->auth->id);
        $where = [];
        $where['build_id'] = ['in', $build_ids];
        // 全部
        $all = ThisModel::where($where)->count();
        // 待审
        $ds = ThisModel::where($where)->where('status', 0)->count();
        // 正常
        $zc = ThisModel::where($where)->where('status', 1)->count();
        // 提醒
        $room_ids = BuildingRoomModel::where([
            'build_id' => ['in', $build_ids],
            'is_remind' => 1
        ])->column('id');
        $tx = ThisModel::where($where)->where('room_id', 'in', $room_ids)->count();
        // 过期
        $gq = ThisModel::where($where)->where('status', 2)->count();

        $this->success('成功', compact('all', 'ds', 'zc', 'tx', 'gq'));
    }


    /**
     * @brief   获取合同详情(房东)
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info()
    {

        $user_id = $this->auth->id;
        $id = $this->request->param('id/d', 0);
        $room_id = $this->request->param('room_id/d', 0);
        if ($room_id) {
            $id = ThisModel::where([
                'room_id' => $room_id,
                //'homeowner_id' => $user_id
            ])->order('id', 'desc')->value('id', 0);
            if (!$id) {
                $this->error('数据不存在');
            }
        } elseif ($id < 1) {
            $this->error('参数错误');
        }

        $where = [
            'id' => $id,
            // 'homeowner_id' => $user_id
        ];

        /*$item = ThisModel::alias('c')
            ->join('building b', 'b.id=c.build_id')
            ->join('house h', 'h.id=c.house_id')
            ->field('c.house_id,c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,
            c.homeowner_phone,c.id,c.status,c.createtime,c.room_name,photo,attachment,ya_type,
            b.images as build_images,h.images as house_images,
            ')
            ->where($where)->find();*/
        $item = ThisModel::field('deletetime,del_uid', true)
            ->with(['board' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            }, 'fixed' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            }, 'pt' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            },'createUser'])
            ->where($where)->find();
        if (!$item) {
            $this->error('数据不存在');
        }
        $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
        $item['createtime'] = date('Y-m-d', $item['createtime']);
        $item['photo'] = get_all_img_path($item['photo']);
        $item['ya_type_text'] = ThisModel::getYaTypeList(1, $item['ya_type']);
        $item['attachment'] = get_all_img_path($item['attachment']);
        $item['user_card_img'] = get_all_img_path($item['user_card_img']);
        $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
        $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
        $item['user_sign_img'] = cdnurl($item['user_sign_img']);
        $this->success('查询成功', $item);

    }


    public function roommate()
    {
        $page_size = $this->request->param('page_size', 10);
        $kw = $this->request->param('kw', '');
        $contract_id = $this->request->param('contract_id/d');

        if ($contract_id < 1) {
            $this->error('合同id不能为空');
        }

        $contract = ThisModel::get($contract_id);
        if (empty($contract)) {
            $this->error('合同不存在');
        }

        $where = [];
        if (!empty($kw)) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }
        $where['id'] = ['in', explode(',', $contract->roommate)];


        $list = CustomerModel::withTrashed()->where($where)
            ->field('id,name,mobile,is_black,create_time')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['create_time_text']);
            });

        $this->success('success', $list);
    }


    public function del()
    {
        $ids = $this->request->param('ids');

        $list = ThisModel::where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {

                $in_record['countent'] = "删除";
                $in_record['ord_id'] = $item['id'];
                $in_record['type'] = 1;
                $in_record['createtime'] = time();
                file_put_contents('rtr1.txt',json_encode($in_record,true));
                Db::name("record")->insertGetId($in_record);

                $item->data('del_uid', $this->auth->id);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error('删除失败');
    }

    /**
     * @brief   获取合同列表(用户)
     *
     */
    public function contractUserLists()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
//            $user_id=7;
            $page = isset($getData['page']) && !empty((int)$getData['page']) ? (int)$getData['page'] : 1;
            $limit = isset($getData['limit']) && !empty((int)$getData['limit']) ? (int)$getData['limit'] : 10;

            $where = [
                'c.user_id' => $user_id
            ];
            $Data = ThisModel::alias('c')
                ->join('building b', 'b.id=build_id')
                ->join('house h', 'h.id=house_id')
                ->field('c.house_id,c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,c.homeowner_phone,c.id,c.status,c.createtime,c.photo,c.room_name,b.images as build_images,h.images as house_images')
                ->where($where)
                ->page($page, $limit)
                ->order('c.status asc,updatetime desc')
                ->select();
            foreach ($Data as $k => $item) {
                $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
                $item['createtime'] = date('Y-m-d H:i', $item['createtime']);

                $item['photo'] = get_all_img_path($item['photo']);

                $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
                $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
                $Data[$k] = $item;
            }
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   获取合同详情(用户)
     * @param
     * @return
     * @author wanchengniuniu
     * @date 2025/2/27
     *
     */
    public function contractUserInfo()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
            $id = isset($getData['id']) && !empty((int)$getData['id']) ? (int)$getData['id'] : 0;
            if (!$id) {
                $this->error('参数错误');
            }

            $where = [
                'c.status' => 1,
                'c.user_id' => $user_id,
                'c.id' => $id
            ];
            $item = ThisModel::alias('c')
                ->join('building b', 'b.id=build_id','left')
                ->join('house h', 'h.id=house_id', 'left')
                ->field('c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,c.homeowner_phone,c.id,c.status,c.createtime,c.room_name,photo,attachment,ya_type,b.images as build_images,h.images as house_images')
                ->where($where)
                ->find();
            if (!$item) {
                $this->error('获取失败');
            }
            $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
            $item['photo'] = get_all_img_path($item['photo']);
            $item['ya_type_text'] = ThisModel::getYaTypeList(1, $item['ya_type']);
            $item['attachment'] = get_all_img_path($item['attachment']);
            $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
            $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
            $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }


    /**
     * @brief   缴费
     * @param
     * @return
     * @author wanchengniuniu
     * @date 2025/2/28
     *
     */
    public function sendMessage()
    {
        $user = $this->auth->getUser();
        $user_id = $user->id;
        $keys = $this->get_keys('sendMessage' . $user_id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }
        //检测缴费记录
        $list = PaymentRecords::field('type,id,status,user_id')->where(['homeowner_id' => $user_id, 'status' => PaymentRecords::STATUS_DEFAULT])->select();
        if (!is_null($list) && !is_array($list)) {
            $list = $list->toArray();
        }
        if (!$list) {
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        //检测发送记录
        $user_ids = array_column($list, 'user_id');
        $log_data = Message::where(['type' => Message::TYPE_ONE])->whereIn('user_id', $user_ids)->select();
        $log_datas = [];
        if (!is_null($log_data) && !is_array($log_data)) {
            $log_datas = $log_data->toArray();
        }
        if (!empty($log_datas)) {
            $log_datas = array_column($log_datas, null, 'other_id');
        }
        $insert_data = [];
        foreach ($list as $v) {
            if (!isset($log_datas[$v['id']])) {
                $insert_data[] = [
                    'type' => Message::TYPE_ONE,
                    'user_id' => $v['user_id'],
                    'other_id' => $v['id'],
                    'title' => '您有一条待缴费消息',
                    'content' => '您有一条待缴费内容',
                ];
            }
        }
        if (!empty($insert_data)) {
            (new Message())->insertAll($insert_data);
        }
        $this->success('提交成功', []);
    }


    /**
     * @brief   通知租客缴费(发消息)
     * @param
     * @return
     * @author wanchengniuniu
     * @date 2025/3/1
     *
     */
    public function sendBiaoMessage()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $homeowner_id = $user->id;
        $keys = $this->get_keys('addBiao' . $homeowner_id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }
        $validate = new \app\api\validate\v2\Contract();
        $check_result = $validate->scene('sendBiaoMessage')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测合同是否有效
        $where = [
            'id' => $getData['pay_log_id']
//            ,'homeowner_id'=>$homeowner_id
        ];
        $info = PaymentRecords::where($where)->find();
        if (!$info) {
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        if ($info['status'] != PaymentRecords::STATUS_DEFAULT) {
            $this->del_rekey($keys);
            $this->error('缴费状态异常');
        }

        $message_data = [
            'type' => Message::TYPE_ONE,
            'user_id' => $info['user_id'],
            'other_id' => $info['id'],
        ];
        if (Message::where($message_data)->find()) {
            $this->success('发送成功');
        }
        $message_data['title'] = '您有一条待缴费修改消息';
        $message_data['content'] = '您有一条待缴费修改内容';
        $res = false;
        try {
            Db::startTrans();
            $re = Message::add($message_data);
            if ($re) {
                $res = true;
                Db::commit();
            } else {
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if (!$res) {
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('发送成功');
    }

    /**
     * @brief   报修
     * @param
     * @return
     * @author wanchengniuniu
     * @date 2025/3/3
     *
     */
    public function sendHouseError()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id = $user->id;
        $keys = $this->get_keys('sendHouseError' . $user_id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }
//        $path=Env::get('root_path');
//        file_put_contents($path.'/public/logs_error.log','time:'.date('Y-m-d H:i:s').json_encode($getData).PHP_EOL,FILE_APPEND);

        $validate = new \app\api\validate\v2\Contract();
        $check_result = $validate->scene('sendHouseError')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }

        //检测合同是否有效
        $info = ThisModel::where(['house_id' => (int)$getData['house_id'], 'status' => ThisModel::STATUS_NORMAL])->find();
        if (!$info) {
            $this->del_rekey($keys);
            $this->error('获取房源信息失败');
        }
        if (!empty($getData['error_photo'])) {
            $photos = explode(',', $getData['error_photo']);
            foreach ($photos as $v) {
                $ext_arr = explode('.', $v);
                if (!in_array($ext_arr[count($ext_arr) - 1], ['png', 'jpeg', 'jpg'])) {
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data = ['error_photo' => $v];
                $check_result = $validate->scene('sendHouseError_error_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        $insert_data = [
            'user_id' => $user_id,
            'contract_id' => $info['id'],
            'homeowner_id' => $info['homeowner_id'],
            'status' => ContractError::STATUS_DEFAULT,
            'type' => $getData['error_type'],
            'photo' => $getData['error_photo'],
            'title' => $getData['error_title'],
        ];
        $re = ContractError::where($insert_data)->find();
        if ($re) {
            $this->error('重复提交');
        }
        $insert_data['createtime'] = time();
        $insert_data['updatetime'] = time();
        $message_data = [
            'type' => Message::TYPE_THREE,
            'user_id' => $info['homeowner_id'],
            'title' => '您有一条待查看报修消息',
            'content' => '您有一条待查看报修内容',
        ];
        //php71 think crud -t user_contract_error --relation=user --relation=user --relation=user_contract --relationforeignkey=user_id --relationforeignkey=homeowner_id --relationforeignkey=contract_id --imagefield=photo
        //php71 think crud -t user_contract_error -d 1
        $res = false;
        try {
            Db::startTrans();
            $id = (new ContractError())->insertGetId($insert_data);
            $message_data['other_id'] = $id;
            $re = Message::add($message_data);
            if ($re && $id) {
                $res = true;
                Db::commit();
            } else {
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if (!$res) {
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('报修成功');
    }

    /**
     * @brief   获取报修类型
     * @param
     * @return
     * @author wanchengniuniu
     * @date 2025/3/3
     *
     */
    public function getHouseErrorType()
    {
        $list = ContractError::getTypeList();
        $this->success('获取成功', $list);
    }

    /**
     * 获取我的报修列表（用户）
     */
    public function baoUserLists()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
            $page = isset($getData['page']) && !empty((int)$getData['page']) ? (int)$getData['page'] : 1;
            $limit = isset($getData['limit']) && !empty((int)$getData['limit']) ? (int)$getData['limit'] : 10;
            $where = ['user_id' => $user_id];
            $Data = ContractError::field('id,title,user_id,status,type,createtime,updatetime')->where($where)
                ->page($page, $limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k => $item) {
//                $item['water_photo']=explode(',',$item['water_photo']);
//                $item['water_photo_path']=isset($item['water_photo'][0])?$item['water_photo'][0]:[];
//                $item['electricity_photo']=explode(',',$item['electricity_photo']);
//                $item['electricity_photo_path']=isset($item['electricity_photo'][0])?$item['electricity_photo'][0]:[];
                $item['status_text'] = ContractError::getStatusList(1, $item['status']);
                $item['type_text'] = ContractError::getTypeList(1, $item['type']);
                $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
                $Data[$k] = $item;
            }
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修列表（房东）
     */
    public function baoLists()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
            $page = isset($getData['page']) && !empty((int)$getData['page']) ? (int)$getData['page'] : 1;
            $limit = isset($getData['limit']) && !empty((int)$getData['limit']) ? (int)$getData['limit'] : 10;
            $where = ['homeowner_id' => $user_id];
            $Data = ContractError::field('id,user_id,title,status,type,createtime,updatetime')->where($where)
                ->page($page, $limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k => $item) {
//                $item['water_photo']=explode(',',$item['water_photo']);
//                $item['water_photo_path']=isset($item['water_photo'][0])?$item['water_photo'][0]:[];
//                $item['electricity_photo']=explode(',',$item['electricity_photo']);
//                $item['electricity_photo_path']=isset($item['electricity_photo'][0])?$item['electricity_photo'][0]:[];
                $item['status_text'] = ContractError::getStatusList(1, $item['status']);
                $item['type_text'] = ContractError::getTypeList(1, $item['type']);
                $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
                $Data[$k] = $item;
            }
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修详情（房东）
     */
    public function baoDetail()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
            $id = isset($getData['id']) && !empty((int)$getData['id']) ? (int)$getData['id'] : 0;
            $where = [
                'homeowner_id' => $user_id,
                'id' => $id];
            $item = ContractError::field('deletetime', true)->where($where)
                ->order('status asc,updatetime desc')
                ->find();
            if (!$item) {
                $this->error('获取失败');
            }
            $item['status_text'] = ContractError::getStatusList(1, $item['status']);
            $item['type_text'] = ContractError::getTypeList(1, $item['type']);
            $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
            $item['updatetime'] = date('Y-m-d H:i', $item['updatetime']);
            $contract_info = \app\common\model\Contract::where(['id' => $item['contract_id']])->find();
            $item['build_address'] = $contract_info['build_address'];
            $item['room_name'] = $contract_info['room_name'];
            $item['homeowner_name'] = $contract_info['homeowner_name'];
            $item['homeowner_phone'] = $contract_info['homeowner_phone'];

            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修详情（用户）
     */
    public function baoUserDetail()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id = $user->id;
            $id = isset($getData['id']) && !empty((int)$getData['id']) ? (int)$getData['id'] : 0;
            $where = [
                'user_id' => $user_id,
                'id' => $id];
            $item = ContractError::field('deletetime', true)->where($where)
                ->order('status asc,updatetime desc')
                ->find();
            $item['status_text'] = ContractError::getStatusList(1, $item['status']);
            $item['type_text'] = ContractError::getTypeList(1, $item['type']);
            $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
            $item['updatetime'] = date('Y-m-d H:i', $item['updatetime']);
            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   线下缴费
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author wanchengniuniu
     * @date 2025/3/3
     */
    public function offlinePayment()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $homeowner_id = $user->id;
            $keys = $this->get_keys('offlinePayment' . $homeowner_id);
            if (!$this->check_repeat($keys, 3)) {
                $this->error('您点击的太快了');
            }
            $validate = new \app\api\validate\v2\Contract();
            $check_result = $validate->scene('offlinePayment')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
            //检测缴费是否有效
            $info = PaymentRecords::where(['id' => $getData['pay_log_id'], 'homeowner_id' => $homeowner_id])->find();
            if (!$info) {
                $this->del_rekey($keys);
                $this->error('获取缴费信息失败');
            }
            if ($info['status'] != PaymentRecords::STATUS_DEFAULT) {
                $this->del_rekey($keys);
                $this->error('缴费状态异常');
            }

            //检测是否有线下缴费订单
            $order_info = OrderPaymentRecords::where(['other_id' => $info['id']])->find();
            $create_data = [];
            if ($order_info) {
                //检测订单是否已支付
                if ($order_info['status'] == 1) {
                    $this->error('记录已支付');
                }
            } else {
                //创建订单
                $create_data = [
                    'order_sn' => create_order_sn('order_sn'),
                    'pay_sn' => create_order_sn('pay_sn'),
                    'other_id' => $info['id'],
                    'money' => $info['money'],
                    'user_id' => $info['user_id'],
                    'status' => OrderPaymentRecords::STATUS_NORMAL,
                    'pay_type' => OrderPaymentRecords::PAY_TYPE_OFFLINE,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
            }
            $message_data = [
                'type' => Message::TYPE_ONE,
                'user_id' => $info['homeowner_id'],
                'title' => '您有一条待查看缴费消息',
                'content' => '您有一条缴费状态已改变',
            ];
            $res = false;
            try {
                Db::startTrans();
                //推送缴费消息
                $re = (new PaymentRecords())->where(['id' => $info['id']])->update(['updatetime' => time(), 'status' => PaymentRecords::STATUS_NORMAL]);
                //处理订单
                if (!empty($create_data)) {
                    $re1 = (new OrderPaymentRecords())->insert($create_data);
                } else {
                    $re1 = (new OrderPaymentRecords())->where(['id' => $order_info['id']])->update(['updatetime' => time(), 'status' => OrderPaymentRecords::STATUS_NORMAL, 'pay_type' => OrderPaymentRecords::PAY_TYPE_OFFLINE]);
                }
                $message_data['other_id'] = $info['id'];
                $re2 = Message::add($message_data);
                if ($re && $re2 && $re1) {
                    $res = true;
                    Db::commit();
                } else {
                    Db::rollback();
                }
            } catch (\DomainException $e) {
                Db::rollback();
            }
            if (!$res) {
                $this->del_rekey($keys);
                $this->error('缴费失败');
            }
            $this->success('缴费成功');
        } else {
            $this->error('请求参数有误');
        }
    }
    //contract_id 合同id
    public function tkDetail(){
        $contract_id = $this->request->post("contract_id");
        $contract_data = Db::name("user_contract")->where(['id'=>$contract_id])->find();
        $room_data = Db::name("building_room")->where(['id'=>$contract_data['room_id']])->find();
        $house_data = Db::name("house")->where(['id'=>$contract_data['house_id']])->find();
        $board = Db::name("user_contract_board")->where(['contract_id'=>$contract_id,'type'=>3])->find();
        $re_data['room_name'] = $room_data['name'];
        $re_data['houseb_name'] = $house_data['name'];
        $re_data['start_time'] = $contract_data['start_time'];
        $re_data['end_time'] = $contract_data['end_time'];
        $re_data['money_zu'] = $contract_data['money_zu'];
        $re_data['rent_way'] = $contract_data['rent_way'];//交租方式，1-每月，2-每2月，3-每3月
        $re_data['user_name'] = $contract_data['user_name'];//
        $re_data['user_phone'] = $contract_data['user_phone'];//
        $re_data['user_card'] = $contract_data['user_card'];//
        $re_data['user_card_img'] = $contract_data['user_card_img'];//
        $re_data['money_electricity'] = $contract_data['money_electricity'];//电费/度
        $re_data['money_water'] = $contract_data['money_water'];//水费/吨
        $re_data['money_ya'] = $contract_data['money_ya'];//押金
        $re_data['gas_price'] = $board['price'];//燃气
        $this->success("退款详情数据",$re_data);

    }
    public function getBoard(){
        $contract_id = $this->request->post("contract_id");//合同ID
        $type = $this->request->post("type");//合同ID
        $data = Db::name("user_contract_board")->where(['contract_id'=>$contract_id,'type'=>$type])->find();
        $this->success("成功",$data);
    }

    /**
     * @return void
     * 退款提交
     */
    public function pushContractTk(){
        file_put_contents("sss1.txt",json_encode($this->request->post(),true));
        $contract_id = $this->request->post("contract_id");//合同ID
        $data = Db::name("user_contract")->where(['id'=>$contract_id])->find();
        $t_data = $this->request->post("t_data/a",[]);//应退款数据
        $f_data = $this->request->post("f_data/a",[]);//应扣数据
        $tk_date = $this->request->post("tk_date");//退房日期
        $tk_type = $this->request->post("tk_type");//退款方式
        $remarks = $this->request->post("remarks");//备注
        $end_money = $this->request->post("end_money",0);//备注
        file_put_contents("sss.txt",json_encode($f_data,true));
        $in_data['t_data'] = json_encode($t_data,true);
        $in_data['f_data'] = json_encode($f_data,true);
        $in_data['tk_date'] = $tk_date;
        $in_data['tk_type'] = $tk_type;
        $in_data['contract_id'] = $contract_id;
        $in_data['remarks'] = $remarks;
        $in_data['createtime'] = time();
        $money = $end_money;
        file_put_contents("tttt.txt",1);
        Db::startTrans();
        try {
            BillModel::create([
                'user_id' => $data['homeowner_id'],
                'contract_id' => $contract_id,
                'status' => 0,
                'money' => $money,
                'year' => date('Y'),
                'month' => date('Y-m'),
                'day' => date('Y-m-d'),
                'category' => '退租',
                'type' => 6,
                'remark' => '退租',
            ]);
            file_put_contents("tttt.txt",2);
            //收支创建
            $add_data['user_id'] = $data['homeowner_id'];
            $add_data['type'] = 2;
            $add_data['money'] = $money;
            //$add_data['classify_id'] = $classify_id;
            //$add_data['ledger_id'] = $ledger_id;
            //$add_data['account_id'] = $account_id;
            $add_data['in_date'] = date('Y-m-d',time());
            //$add_data['images'] = $images;
            $add_data['house_id'] = $data['house_id'];
            $add_data['remarks'] = '退租';
            $add_data['str_type'] = '退租';
            $add_data['createtime'] = time();
            Db::name("szinfo")->insertGetId($add_data);
            file_put_contents("tttt.txt",3);
            Db::name("user_contract_refund")->insertGetId($in_data);
            Db::name("user_contract")->where(['id'=>$contract_id])->update(['status'=>3]);
            Db::name("house")->where(['id'=>$data['house_id']])->update(['status'=>2]);
            Db::name("building_room")->where(['id'=>$data['room_id']])->update(['status'=>0]);
            file_put_contents("tttt.txt",4);
            file_put_contents("ttt1t.txt",$contract_id);
            $in_record['countent'] = "退租成功";
            $in_record['ord_id'] = $contract_id;
            $in_record['type'] = 1;
            $in_record['createtime'] = time();
            file_put_contents('rtr1.txt',json_encode($in_record,true));
            Db::name("record")->insertGetId($in_record);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            trace('合同退租失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }

        $this->success("退租成功");
    }
    //固定费用
    public function getContractFixed(){
       $list = Db::name("user_contract_fixed")->select();
       $this->success("固定费用",$list);
    }

    public function contractAddFecords(){
        $house_id = $this->request->post("house_id");
        $contract_data = Db::name("user_contract")->where(['house_id'=>$house_id])->find();
        if(!$contract_data){
            $this->error("没有合同信息");
        }
        $id = $contract_data['id'];
        $str_date = $this->request->post("str_date",'');
        $end_date = $this->request->post("end_date",'');
        $rename = $this->request->post("name",'');
        $money = $this->request->post("money",0);
        $month = $this->request->post("month",1);
        $contract = ThisModel::get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }
        Db::startTrans();
        try {
            // =========  生成账单 =========
            //首次租金
            $rent_date = date('Y-m-' . $contract['rent_day']);
            $period = $str_date . '至' . $end_date;

            $first_money = $contract['first_zu'];
            //$fixed_money = BuildingRoomFixedModel::where('room_id', $contract['room_id'])->sum('price');

            //$first_money = bcadd($first_money, $fixed_money, 2);

            if ($first_money > 0) {
                $other_data = [
                    [
                        'name' => '首次租金',
                        'money' => $first_money,
                    ]
                ];
                $first_money = $month * $first_money;
                $name = '租金';
                if($money > 0){
                    $first_money = $money;
                    $name = $rename;
                }
                $bill = BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 0,
                    'money' => $first_money,
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => $name,
                    'type' => 1,
                    'remark' => $name,
                    'period' => $period,
                    'is_first' => 1,
                    'other_data' => json_encode($other_data,JSON_UNESCAPED_UNICODE),
                ], true);
                //收支创建
                $add_data['user_id'] = $contract['homeowner_id'];
                $add_data['type'] = 2;
                $add_data['money'] = $first_money;
                //$add_data['classify_id'] = $classify_id;
                //$add_data['ledger_id'] = $ledger_id;
                //$add_data['account_id'] = $account_id;
                $add_data['in_date'] = date('Y-m-d',time());
                //$add_data['images'] = $images;
                $add_data['house_id'] = $contract['house_id'];
                $add_data['remarks'] = '房租押金';
                $add_data['str_type'] = $name;
                $add_data['createtime'] = time();
                Db::name("szinfo")->insertGetId($add_data);


                PaymentRecords::create([
                    'homeowner_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'relation_id' => $bill->id,
                    'user_id' => $contract->user_id,
                    'type' => PaymentRecords::TYPE_FANG,
                    'status' => PaymentRecords::STATUS_DEFAULT,
                    'money' => $first_money,
                ],true);
            }

            // 房租押金
           /* if ($contract['money_ya'] > 0) {
                BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 2,
                    'money' => $contract['money_ya'],
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => '押金',
                    'type' => 2,
                    'remark' => '房租押金',
                    'expire_date' => $contract['end_time'],
                ]);
                //收支创建
                $add_data['user_id'] = $contract['homeowner_id'];
                $add_data['type'] = 2;
                $add_data['money'] = $contract['money_ya'];
                //$add_data['classify_id'] = $classify_id;
                //$add_data['ledger_id'] = $ledger_id;
                //$add_data['account_id'] = $account_id;
                $add_data['in_date'] = date('Y-m-d',time());
                //$add_data['images'] = $images;
                $add_data['house_id'] = $contract['house_id'];
                $add_data['remarks'] = '房租押金';
                $add_data['str_type'] = '房租押金';
                $add_data['createtime'] = time();
                Db::name("szinfo")->insertGetId($add_data);
            }


            // 配套押金
            if (!empty($contract['pt'])) {
                $pt_money = array_sum(array_column($contract['pt'], 'deposit'));
                if ($pt_money > 0) {
                    BillModel::create([
                        'user_id' => $contract['homeowner_id'],
                        'contract_id' => $id,
                        'status' => 2,
                        'money' => $pt_money,
                        'year' => date('Y'),
                        'month' => date('Y-m'),
                        'day' => date('Y-m-d'),
                        'category' => '押金',
                        'type' => 2,
                        'remark' => '配套设备押金',
                        'expire_date' => $contract['end_time'],
                    ]);
                }
            }*/

            $contract->status = 1;
            $contract->save();

            // 更新房间状态
            $room = BuildingRoomModel::get($contract->room_id);
            $room->status = 3;
            $room->save();



            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            trace('失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }
        $this->success("创建成功");
    }
}
